import { useState, useEffect } from 'react';
import { Box, Text, Flex, Checkbox, Heading, Avatar, VStack, Spinner, Alert, AlertIcon } from '@chakra-ui/react';
import Pagination from '@/components/Pagination/index'; // 引入你之前优化的Pagination组件

interface IProps {
    itemsPerPage?: number;
    showPagination: boolean;
}

interface Comment {
    id: number;
    username: string;
    avatarUrl: string;
    content: string;
    timestamp: string;
}

function Comment({ comment }: { comment: Comment }) {
    return (
        <Flex alignItems="center" mb={4}>
            <Avatar size="sm" src={comment.avatarUrl} mr={4} />
            <VStack align="start">
                <Text fontWeight="bold">{comment.username}</Text>
                <Text>{comment.content}</Text>
                <Text fontSize="sm" color="gray.500">
                    {comment.timestamp}
                </Text>
            </VStack>
        </Flex>
    );
}

const CommentSection = ({ itemsPerPage = 5, showPagination }: IProps) => {
    const [currentPage, setCurrentPage] = useState(1);
    const [comments, setComments] = useState<Comment[]>([]);
    const [totalPages, setTotalPages] = useState(0);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    // 获取分页评论数据
    const fetchComments = async (page: number) => {
        setLoading(true);
        try {
            const response = await fetch(`https://api.example.com/comments?page=${page}&limit=${itemsPerPage}`);
            if (!response.ok) {
                throw new Error('Failed to fetch comments');
            }
            const data = await response.json();
            setComments(data.comments);
            setTotalPages(data.totalPages); // 假设后端返回总页数
            setError(null);
        } catch (err) {
            console.error('Error fetching comments:', err);
            setError('无法加载评论，请稍后再试。');
        } finally {
            setLoading(false);
        }
    };

    // 初始加载第一页评论
    useEffect(() => {
        fetchComments(currentPage);
    }, [currentPage]);

    return (
        <Box mb={10}>
            <Heading as="h2" size="lg" mb={4}>
                热门评论
            </Heading>

            {/* 加载中指示器 */}
            {loading && (
                <Flex justifyContent="center" mt={4}>
                    <Spinner size="lg" />
                </Flex>
            )}

            {/* 错误提示 */}
            {error && (
                <Alert status="error" mb={4}>
                    <AlertIcon />
                    {error}
                </Alert>
            )}

            {/* 评论列表 */}
            {!loading && !error && (
                <>
                    <Text fontWeight="bold" mb={2}>
                        {comments.length} 条
                    </Text>
                    <VStack spacing={4} align="start">
                        {comments.map((comment) => (
                            <Comment key={comment.id} comment={comment} />
                        ))}
                    </VStack>
                </>
            )}

            {/* 分页控件 */}
            {showPagination && !loading && !error && (
                <Pagination
          
                    totalPages={totalPages}
                    onPageChange={(page) => {
                        setCurrentPage(page);
                    }}
                />
            )}
        </Box>
    );
};

export default CommentSection;